Skip to main content

map 排序

gosort包提供了接口

type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}

按照需要的排序规则实现其中的方法就好了。 比如你题目说的需要按照时间的先后顺序来排序,那么 Less方法的实现,就是用对象的 Time字段来比较大小。

如下是一个Demo,按照人的年龄来排序。

package main

import (
"fmt"
"sort"
)

// Person struct
type Person struct {
Name string
Age int
}

// Persons a set of person
type Persons []Person

// Len return count
func (p Persons) Len() int {
return len(p)
}

// Less return bigger true
func (p Persons) Less(i, j int) bool {
return p[i].Age < p[j].Age
}

// Swap swap items
func (p Persons) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}

func main() {
ps := Persons{}
ps = append(ps, Person{
"张三", 31,
})
ps = append(ps, Person{
"李四", 23,
})
ps = append(ps, Person{
"王五", 40,
})

sort.Sort(ps)
fmt.Println(ps)
}